package Concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * Description：
 * Author: zhangc
 * Date：2017/10/5 21:00
 */
public class ReadWriteLockTest {


    static volatile Integer second = 0;
    private static ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = reentrantReadWriteLock.readLock();
    private static Lock writeLock = reentrantReadWriteLock.writeLock();
    private static ExecutorService service = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        for (int i = 0; i < 8; i++) {
            service.execute(new MyRead());
        }
        service.execute(new MyWrite());
    }

    static class MyRead implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    readLock.lock();
                    System.out.println("CurrentSecond : " + second);
                } finally {
                    readLock.unlock();
                }

            }
        }
    }

    static class MyWrite implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                writeLock.lock();
                try {
                    second++;
                } finally {
                    writeLock.unlock();
                }

            }
        }
    }


}
